//
//  DMInterstitialManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/7/9.
//

#import "DMInterstitialManager.h"
#if __has_include(<IronSource/IronSource.h>)
#import <IronSource/IronSource.h>
#define IRONSOURCE_SDK_AVAILABLE 1
#else
#define IRONSOURCE_SDK_AVAILABLE 0
#endif
#import <UIKit/UIKit.h>
#import "../../Utils/Logger/IMLogUtils.h"
#import "DMConfigReader.h"
#import "DMInterstitialScenes.h"
#import "DMInterstitialSceneInterceptor.h"
#import "DMThinkingManager.h"
#import "DMCommercialManager.h"
#import <AdjustSdk/AdjustSdk.h>

// Fallback 场景常量（当头文件未能正确暴露时保持可编译）
#ifndef SCENE_INTER_LEVEL_WIN
#define SCENE_INTER_LEVEL_WIN @"interstitial_default_scene"
#endif

// 前置声明以避免在部分 SDK 不可用时的类型错误
@protocol DMAdDelegate;
@class LPMInterstitialAd, LPMAdInfo;
@class DMCommercialManager, DMConfigReader, DMInterstitialSceneInterceptor, DMThinkingManager, DMAdManager;


// 在 IronSource SDK 可用时采用 LPMInterstitialAdDelegate，否则使用空扩展避免重复定义
#if IRONSOURCE_SDK_AVAILABLE
@interface DMInterstitialManager ()<LPMInterstitialAdDelegate>
#else
@interface DMInterstitialManager ()
#endif

@property (nonatomic, assign) BOOL hasShowAd;
#if IRONSOURCE_SDK_AVAILABLE
@property (nonatomic, strong) LPMInterstitialAd *interstitialAd;
#else
@property (nonatomic, strong) id interstitialAd;
#endif

@property (nonatomic, copy, readwrite) NSString *currentScene;
@property (nonatomic, strong) NSTimer *autoTriggerTimer;

// 事件打点相关属性
@property (nonatomic, assign) NSTimeInterval loadStartTime;
@property (nonatomic, strong) NSString *currentAdUnitId;
@property (nonatomic, strong) NSString *currentAdScene;

// 双广告位支持的私有属性
#if IRONSOURCE_SDK_AVAILABLE
@property (nonatomic, strong) LPMInterstitialAd *primaryInterstitialAdView;
@property (nonatomic, strong) LPMInterstitialAd *secondaryInterstitialAdView;
#else
@property (nonatomic, strong) id primaryInterstitialAdView;
@property (nonatomic, strong) id secondaryInterstitialAdView;
#endif
@property (nonatomic, assign) BOOL isLoadingPrimary;
@property (nonatomic, assign) BOOL isLoadingSecondary;
@property (nonatomic, assign) NSTimeInterval primaryAdLoadTime;
@property (nonatomic, assign) NSTimeInterval secondaryAdLoadTime;

// 上述属性在头文件中已声明为可写，不需重复在类扩展中声明

@end

@implementation DMInterstitialManager {
    // 若需自管 delegate，可在此定义；当前改为使用属性默认合成，避免编译错误
}
static DMInterstitialManager *_interstitial = nil;

- (void)setAdDelegate:(id)delegate { self.delegate = delegate; }

+ (instancetype)shareInterstitialManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _interstitial = [[self alloc] init];
        [IMLogUtils info:IMLogTagSDKInit format:@"📱 [Interstitial] 单例管理器创建成功"];
        
        // 双广告位支持初始化
        _interstitial.isDualAdEnabled = [DMCommercialManager isDualAdEnabledForAdType:@"interstitial"];
        if (_interstitial.isDualAdEnabled) {
            // 修正主/备广告位 ID 初始化错误：主用 primary，备用 secondary
            _interstitial.currentPrimaryAdUnitId = [DMConfigReader primaryInterAdUnitId];
            _interstitial.currentSecondaryAdUnitId = [DMConfigReader secondaryInterAdUnitId];
            _interstitial.isLoadingPrimary = NO;
            _interstitial.isLoadingSecondary = NO;
            _interstitial.isPrimaryAdLoaded = NO;
            _interstitial.isSecondaryAdLoaded = NO;
            _interstitial.primaryAdECPM = 0.0;
            _interstitial.secondaryAdECPM = 0.0;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 双广告位模式已启用 - 主广告位: %@, 备用广告位: %@", _interstitial.currentPrimaryAdUnitId, _interstitial.currentSecondaryAdUnitId];
        } else {
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 单广告位模式"];
        }
        
        // 初始化插屏广告重试设置
        [_interstitial initializeRetrySettings];
    });
    return _interstitial;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _interTimeSceneEnabled = YES; // 默认启用时间场景
        _currentScene = SCENE_INTER_LEVEL_WIN; // 默认场景
    }
    return self;
}

- (void)interstitialDelegate
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 开始设置代理和初始化插屏广告"];
    
    // 初始化时预加载一个插屏广告
    // 根据是否启用双广告位模式选择加载方式
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 启用双广告位模式，开始加载双广告位"];
        [self loadDualInterstitialAds];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 单广告位模式，开始加载单广告位"];
        [self loadInter];
    }
}

- (void)showInterstitial
{
    // 兼容旧接口，使用默认场景
    [self showInterAd:SCENE_INTER_LEVEL_WIN];
}

#pragma mark - Root View Controller Utilities

// 递归获取顶层视图控制器（处理导航、标签、模态层级）
- (UIViewController *)topMostViewControllerFrom:(UIViewController *)vc {
    if (!vc) { return nil; }
    UIViewController *current = vc;
    while (current.presentedViewController) {
        current = current.presentedViewController;
    }
    if ([current isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)current;
        UIViewController *visible = nav.visibleViewController ?: nav.topViewController;
        return [self topMostViewControllerFrom:visible ?: current];
    }
    if ([current isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tab = (UITabBarController *)current;
        UIViewController *selected = tab.selectedViewController ?: (tab.viewControllers.count > 0 ? tab.viewControllers.firstObject : nil);
        return [self topMostViewControllerFrom:selected ?: current];
    }
    return current;
}

// 更稳健地获取根控制器：优先 iOS13+ 的 UIWindowScene，其次 keyWindow，最后遍历 windows
- (UIViewController *)getRootViewController {
    UIViewController *rootVC = nil;
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *scenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in scenes) {
            if (scene.activationState != UISceneActivationStateForegroundActive) { continue; }
            if (![scene isKindOfClass:[UIWindowScene class]]) { continue; }
            UIWindowScene *ws = (UIWindowScene *)scene;
            for (UIWindow *window in ws.windows) {
                if (window.isKeyWindow) { rootVC = window.rootViewController; break; }
            }
            if (!rootVC && ws.windows.count > 0) {
                rootVC = ws.windows.firstObject.rootViewController;
            }
            if (rootVC) { break; }
        }
    }
    if (!rootVC) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        UIWindow *legacyKey = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
        if (legacyKey) { rootVC = legacyKey.rootViewController; }
    }
    if (!rootVC) {
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *w in windows) {
            if (w.isKeyWindow) { rootVC = w.rootViewController; break; }
        }
        if (!rootVC && windows.count > 0) {
            rootVC = windows.firstObject.rootViewController;
        }
    }
    return rootVC ? [self topMostViewControllerFrom:rootVC] : nil;
}

- (void)showInterAd:(NSString *)adScene
{
    if (!adScene || adScene.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ 广告场景为空，使用默认场景"];
        adScene = SCENE_INTER_LEVEL_WIN;
    }
    
    // 时间场景拦截检查
    if (self.interTimeSceneEnabled && [[DMInterstitialSceneInterceptor sharedInterceptor] shouldInterceptScene:adScene]) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 🚫 场景 %@ 被拦截器拦截", adScene];
        // 通知代理展示失败
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
            NSError *error = [NSError errorWithDomain:@"DMInterstitial" code:-4 userInfo:@{NSLocalizedDescriptionKey: @"场景被拦截器拦截"}];
            DMInterstitialScene sceneEnum = [DMInterstitialScenes sceneEnumFromString:adScene];
            [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
        }
        return;
    }
    
    self.currentScene = adScene;
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] ========== 开始展示插屏广告 [%@] ==========", adScene];
    [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"WDOrientation"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 设置屏幕方向标识: WDOrientation = 2"];
    
    // SDK_ad_show_request 广告展示请求事件打点
    NSDictionary *showRequestParams = @{
        @"w_ad_scene": adScene ?: @"interstitial_show",
        @"w_ad_type": @"interstitial"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_show_request"];
    
    // 双广告位模式下选择最优广告位
    if (self.isDualAdEnabled) {
        NSString *optimalAdUnitId = [self selectOptimalAdUnitId];
        
        if ([optimalAdUnitId isEqualToString:self.currentPrimaryAdUnitId] && self.primaryInterstitialAdView && [self.primaryInterstitialAdView isAdReady]) {
            self.interstitialAd = self.primaryInterstitialAdView;
            self.currentAdUnitId = self.currentPrimaryAdUnitId;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 选择主广告位展示: %@", optimalAdUnitId];
        } else if ([optimalAdUnitId isEqualToString:self.currentSecondaryAdUnitId] && self.secondaryInterstitialAdView && [self.secondaryInterstitialAdView isAdReady]) {
            self.interstitialAd = self.secondaryInterstitialAdView;
            self.currentAdUnitId = self.currentSecondaryAdUnitId;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 选择备用广告位展示: %@", optimalAdUnitId];
        }
    }
    
    if (self.interstitialAd && [self.interstitialAd isAdReady])
    {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] ✅ 插屏广告准备就绪，开始展示"];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 广告实例: %@", self.interstitialAd];

        UIViewController *rootViewController = [self getRootViewController];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 获取根控制器: %@", rootViewController];
        if (!rootViewController) {
            [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ 未能获取顶层视图控制器，取消展示"];
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
                NSError *error = [NSError errorWithDomain:@"DMInterstitialManager" code:1003 userInfo:@{NSLocalizedDescriptionKey: @"无法获取根视图控制器"}];
                [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
            }
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
#if IRONSOURCE_SDK_AVAILABLE
            [self.interstitialAd showAdWithViewController:rootViewController placementName:adScene];
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 调用 showAdWithViewController 完成"];
#else
            [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ IronSource SDK 不可用，无法展示广告"];
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
                NSError *error = [NSError errorWithDomain:@"DMInterstitialManager" code:1002 userInfo:@{NSLocalizedDescriptionKey: @"IronSource SDK 不可用"}];
                [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
            }
#endif
        });
    }else{
        [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ 插屏广告未准备就绪"];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 广告实例存在: %@", self.interstitialAd ? @"YES" : @"NO"];
        [IMLogUtils debug:IMLogTagAd format:@"📱 [Interstitial] 广告是否就绪: %@", (self.interstitialAd && [self.interstitialAd isAdReady]) ? @"YES" : @"NO"];
        
        // 通知展示失败
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
            NSError *error = [NSError errorWithDomain:@"DMInterstitialManager" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"广告未准备就绪"}];
            [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:adScene error:error];
        }
        
        self.hasShowAd = YES;
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 设置 hasShowAd = YES，将在广告加载完成后自动展示"];
        if (self.isDualAdEnabled) {
            [self loadDualInterstitialAds];
        } else {
            [self loadInter];
        }
     }
}

- (void)setInterTimeSceneEnable:(BOOL)enable {
    self.interTimeSceneEnabled = enable;
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 设置时间场景拦截: %@", enable ? @"启用" : @"禁用"];
}

- (void)loadInterstitial {
    [self loadInter];
}

- (BOOL)isAdReady {
    #if IRONSOURCE_SDK_AVAILABLE
    return self.interstitialAd && [self.interstitialAd isAdReady];
    #else
    return NO;
    #endif
}

- (void)loadInter
{
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] ========== 开始加载插屏广告 =========="];
    
    // 记录加载开始时间
    self.loadStartTime = [[NSDate date] timeIntervalSince1970];
    
    // 获取广告位ID
    NSString *adUnitId = [DMConfigReader primaryInterAdUnitId];
    self.currentAdUnitId = adUnitId;
    
    // 记录广告加载请求到DMCommercialManager
    [[DMCommercialManager sharedInstance] recordAdLoadRequest:adUnitId adType:@"interstitial"];
    
    // SDK_ad_fill_request 广告填充请求事件打点
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": self.currentAdUnitId ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_fill_request"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 埋点事件已发送: adLoad"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        #if IRONSOURCE_SDK_AVAILABLE
        // 创建 LPMInterstitialAd
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 创建 LPMInterstitialAd 实例"];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdUnit ID: %@", self.currentAdUnitId ?: @""];

        self.interstitialAd = [[LPMInterstitialAd alloc] initWithAdUnitId:self.currentAdUnitId];
        [self.interstitialAd setDelegate:self];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 设置代理完成: %@", self];

        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 调用 loadAd 开始加载广告"];
        [self.interstitialAd loadAd];
        #else
        [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ IronSource SDK 不可用，跳过加载"];
        #endif
    });
}

#pragma mark - LPMInterstitialAdDelegate

#if IRONSOURCE_SDK_AVAILABLE
- (void)didLoadAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] ✅ ========== 插屏广告加载成功 =========="];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdInfo详情:"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - AdUnit: %@", adInfo.adUnitId ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - Revenue: $%.6f", adInfo.revenue ? adInfo.revenue.doubleValue : 0.0];
    
    // 双广告位模式下判断是主广告位还是备用广告位加载成功
    NSString *adSource = @"single";
    NSTimeInterval fillTime = 0;
    if (self.isDualAdEnabled) {
        if ([adInfo.adUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
            self.isPrimaryAdLoaded = YES;
            self.isLoadingPrimary = NO;
            self.primaryAdECPM = adInfo.revenue ? adInfo.revenue.doubleValue : 0.0;
            adSource = @"primary";
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
            fillTime = (currentTime - self.primaryAdLoadTime) * 1000;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 主广告位加载成功，ECPM: $%.6f", self.primaryAdECPM];
        } else if ([adInfo.adUnitId isEqualToString:self.currentSecondaryAdUnitId]) {
            self.isSecondaryAdLoaded = YES;
            self.isLoadingSecondary = NO;
            self.secondaryAdECPM = adInfo.revenue ? adInfo.revenue.doubleValue : 0.0;
            adSource = @"secondary";
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
            fillTime = (currentTime - self.secondaryAdLoadTime) * 1000;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 备用广告位加载成功，ECPM: $%.6f", self.secondaryAdECPM];
        }
    } else {
        NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
        fillTime = (currentTime - self.loadStartTime) * 1000;
    }
    
    // 重置重试状态
    [self resetRetryState];
    
    // SDK_ad_fill_success 广告填充成功事件打点
    NSDictionary *fillSuccessParams = @{
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": adInfo.adUnitId ?: @"",
        @"w_fill_time": @(fillTime),
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_source": adSource
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_fill_success"];
    
    // 通知代理加载成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadInterstitialForScene:adId:)]) {
        NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        [self.delegate dmAdManager:(DMAdManager *)self didLoadInterstitialForScene:scene adId:adInfo.adUnitId];
    }
    
    if (self.hasShowAd)
    {
        self.hasShowAd = NO;
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 检测到延迟展示标志，立即展示广告"];
        [self showInterAd:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
    }
}

- (void)didFailToLoadAdWithAdUnitId:(NSString *)adUnitId error:(NSError *)error {
    [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ ========== 插屏广告加载失败 =========="];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdUnit ID: %@", adUnitId];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 错误信息: %@", error.localizedDescription];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [Interstitial] 错误代码: %ld", (long)error.code];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 错误域: %@", error.domain];
    if (error.userInfo) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 错误详情: %@", error.userInfo];
    }
    
    // 双广告位模式下判断失败的广告位
    NSString *adSource = @"single";
    NSTimeInterval fillTime = 0;
    BOOL shouldSwitchToSecondary = NO;
    
    if (self.isDualAdEnabled) {
        if ([adUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
            self.isPrimaryAdLoaded = NO;
            self.isLoadingPrimary = NO;
            adSource = @"primary";
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
            fillTime = (currentTime - self.primaryAdLoadTime) * 1000;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 主广告位加载失败"];
            
            // 检查是否需要切换到备用广告位
            if (self.isSecondaryAdLoaded) {
                shouldSwitchToSecondary = YES;
            }
        } else if ([adUnitId isEqualToString:self.currentSecondaryAdUnitId]) {
            self.isSecondaryAdLoaded = NO;
            self.isLoadingSecondary = NO;
            adSource = @"secondary";
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
            fillTime = (currentTime - self.secondaryAdLoadTime) * 1000;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 备用广告位加载失败"];
        }
    } else {
        NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
        fillTime = (currentTime - self.loadStartTime) * 1000;
    }
    
    // SDK_ad_fill_fail 广告填充失败事件打点
    NSDictionary *fillFailParams = @{
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": adUnitId ?: @"",
        @"w_fill_time": @(fillTime),
        @"w_error_code": @(error.code),
        @"w_error_msg": error.localizedDescription ?: @"",
        @"w_ad_source": adSource
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_fill_fail"];
    
    // 双广告位模式下的切换逻辑
    if (shouldSwitchToSecondary) {
        [self switchToSecondaryAdIfNeeded];
    }
    
    // 通知代理加载失败
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadInterstitialForScene:error:)]) {
        NSString *sceneString = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        [self.delegate dmAdManager:(DMAdManager *)self didFailToLoadInterstitialForScene:sceneString error:error];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 立即重新尝试加载..."];
    // 增加失败计数
    self.totalFailures++;
    
    // 使用智能重试机制
    if ([self shouldRetry]) {
        NSTimeInterval delay = [self calculateRetryDelay];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 安排智能重试 - 延迟%.1f秒后重试", delay];
        [self scheduleRetryWithDelay:delay];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 停止重试 - 已达到重试限制或失败率过高"];
    }
}

- (void)didDisplayAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] ✅ ========== 插屏广告展示成功 =========="];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdInfo详情:"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - Revenue: $%.6f", adInfo.revenue ? adInfo.revenue.doubleValue : 0.0];
    
    // SDK_ad_show_success 广告展示成功事件打点
    NSDictionary *showSuccessParams = @{
        @"w_ad_scene": self.currentScene ?: @"interstitial_show",
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": adInfo.adUnitId ?: @"",
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_show_success"];
    
    // SDK_ad_show_completed 广告播放完成事件打点
    NSDictionary *showCompletedParams = @{
        @"w_ad_scene": self.currentScene ?: @"interstitial_show",
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": adInfo.adUnitId ?: @"",
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_completed" properties:showCompletedParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_show_completed"];
    
    // AD_Inter_show 插屏广告展示事件上报
    double ecpm = adInfo.revenue ? adInfo.revenue.doubleValue * 1000 : 0.0;
    NSDictionary *interShowParams = @{
        @"w_scene": self.currentScene ?: @"interstitial_show",
        @"w_revenue": @(ecpm)
    };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_Inter_show" jsonStr:interShowParams];
    
    double revenueUSD = [[NSUserDefaults standardUserDefaults] doubleForKey:@"Inter_RevenueUSD"];
    if (revenueUSD > 0) {

        ADJAdRevenue *adjustAdRevenue = [[ADJAdRevenue alloc] initWithSource:@"ironsource_sdk"];
        [adjustAdRevenue setRevenue:revenueUSD currency:@"USD"];
        [adjustAdRevenue setAdRevenueNetwork:adInfo.adNetwork];
        [adjustAdRevenue setAdRevenueUnit:adInfo.adUnitId];
        [adjustAdRevenue setAdRevenuePlacement:adInfo.placementName];
        [adjustAdRevenue addPartnerParameter:@"ad_format" value: adInfo.adUnitId];
        [adjustAdRevenue addPartnerParameter:@"ad_unit_id" value: adInfo.instanceId];
        [adjustAdRevenue addPartnerParameter:@"auctionId" value:adInfo.auctionId];
        [Adjust trackAdRevenue:adjustAdRevenue];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件上报: AD_Inter_show, w_revenue: %.2f", ecpm];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 回调通知: Show"];
    
    // 记录场景展示到拦截器
    [[DMInterstitialSceneInterceptor sharedInterceptor] recordSceneShow:self.currentScene ?: SCENE_INTER_LEVEL_WIN];
    
    // 通知代理展示成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowInterstitialForScene:adId:)]) {
        NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        [self.delegate dmAdManager:(DMAdManager *)self didShowInterstitialForScene:scene adId:adInfo.adUnitId];
    }
}

- (void)didFailToDisplayAdWithAdInfo:(LPMAdInfo *)adInfo error:(NSError *)error {
    [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ ========== 插屏广告展示失败 =========="];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdInfo: %@", adInfo];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 错误信息: %@", error.localizedDescription];
    [IMLogUtils debug:IMLogTagAd format:@"📱 [Interstitial] 错误代码: %ld", (long)error.code];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 错误域: %@", error.domain];
    if (error.userInfo) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 错误详情: %@", error.userInfo];
    }
    
    // SDK_ad_show_fail 广告展示失败事件打点
    NSDictionary *showFailParams = @{
        @"w_ad_scene": self.currentScene ?: @"interstitial_show",
        @"w_ad_type": @"interstitial",
        @"w_error_code": [NSString stringWithFormat:@"%ld", (long)error.code],
        @"w_error_msg": error.localizedDescription ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_show_fail"];
    
    // 通知代理展示失败
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowInterstitialForScene:error:)]) {
        NSString *sceneString = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        [self.delegate dmAdManager:(DMAdManager *)self didFailToShowInterstitialForScene:sceneString error:error];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重新加载广告..."];
    // 增加失败计数
    self.totalFailures++;
    
    // 使用智能重试机制
    if ([self shouldRetry]) {
        NSTimeInterval delay = [self calculateRetryDelay];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 安排智能重试 - 延迟%.1f秒后重试", delay];
        [self scheduleRetryWithDelay:delay];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 停止重试 - 已达到重试限制或失败率过高"];
    }
}
#endif

- (void)didClickAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 👆 ========== 插屏广告被点击 =========="];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdInfo详情:"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - Revenue: $%.6f", adInfo.revenue ? adInfo.revenue.doubleValue : 0.0];
    
    // SDK_ad_show_click 广告点击事件打点
    NSDictionary *clickParams = @{
        @"w_ad_scene": self.currentScene ?: @"interstitial_show",
        @"w_ad_type": @"interstitial",
        @"w_ad_unit_id": adInfo.adUnitId ?: @"",
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 事件打点: SDK_ad_show_click"];
    
    // 通知代理点击事件
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickInterstitialForScene:adId:)]) {
        NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        [self.delegate dmAdManager:(DMAdManager *)self didClickInterstitialForScene:scene adId:adInfo.adUnitId];
    }
}

- (void)didCloseAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 🔄 ========== 插屏广告关闭 =========="];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] AdInfo详情:"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    
    self.hasShowAd = NO;
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重置状态: hasShowAd = NO"];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 回调通知: Finish"];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 埋点事件已发送: adClose"];
    
    // 通知代理关闭事件
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didCloseInterstitialForScene:adId:)]) {
        NSString *scene = self.currentScene ?: SCENE_INTER_LEVEL_WIN;
        [self.delegate dmAdManager:(DMAdManager *)self didCloseInterstitialForScene:scene adId:adInfo.adUnitId];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 开始重新加载下一个广告..."];
    // 使用智能重试机制重新加载下一个广告
    if ([self shouldRetry]) {
        NSTimeInterval delay = [self calculateRetryDelay];
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 安排智能重试 - 延迟%.1f秒后重新加载下一个广告", delay];
        [self scheduleRetryWithDelay:delay];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 停止重试 - 已达到重试限制或失败率过高"];
    }
}

#pragma mark - 双广告位支持方法

- (void)loadDualInterstitialAds {
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] ========== 开始加载双广告位插屏广告 =========="];
    
    // 获取双广告位配置
    self.isDualAdEnabled = [DMCommercialManager isDualAdEnabledForAdType:@"interstitial"];
    
    if (!self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 双广告位未启用，使用单广告位模式"];
        [self loadInter];
        return;
    }
    
    self.currentPrimaryAdUnitId = [DMConfigReader primaryInterAdUnitId];
    self.currentSecondaryAdUnitId = [DMConfigReader secondaryInterAdUnitId];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 主广告位ID: %@", self.currentPrimaryAdUnitId];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 备用广告位ID: %@", self.currentSecondaryAdUnitId];
    
    // 同时加载主广告位和备用广告位
    [self loadPrimaryInterstitialAd];
    [self loadSecondaryInterstitialAd];
}

- (void)loadPrimaryInterstitialAd {
    if (self.isLoadingPrimary || !self.currentPrimaryAdUnitId) {
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 开始加载主广告位: %@", self.currentPrimaryAdUnitId];
    self.isLoadingPrimary = YES;
    self.isPrimaryAdLoaded = NO;
    self.primaryAdLoadTime = [[NSDate date] timeIntervalSince1970];
    
    dispatch_async(dispatch_get_main_queue(), ^{
#if IRONSOURCE_SDK_AVAILABLE
        self.primaryInterstitialAdView = [[LPMInterstitialAd alloc] initWithAdUnitId:self.currentPrimaryAdUnitId];
        [self.primaryInterstitialAdView setDelegate:self];
        [self.primaryInterstitialAdView loadAd];
#else
        [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ IronSource SDK 不可用，跳过主广告位加载"];
#endif
    });
}

- (void)loadSecondaryInterstitialAd {
    if (self.isLoadingSecondary || !self.currentSecondaryAdUnitId) {
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 开始加载备用广告位: %@", self.currentSecondaryAdUnitId];
    self.isLoadingSecondary = YES;
    self.isSecondaryAdLoaded = NO;
    self.secondaryAdLoadTime = [[NSDate date] timeIntervalSince1970];
    
    dispatch_async(dispatch_get_main_queue(), ^{
#if IRONSOURCE_SDK_AVAILABLE
        self.secondaryInterstitialAdView = [[LPMInterstitialAd alloc] initWithAdUnitId:self.currentSecondaryAdUnitId];
        [self.secondaryInterstitialAdView setDelegate:self];
        [self.secondaryInterstitialAdView loadAd];
#else
        [IMLogUtils warning:IMLogTagAd format:@"📱 [Interstitial] ❌ IronSource SDK 不可用，跳过备用广告位加载"];
#endif
    });
}

- (NSString *)selectOptimalAdUnitId {
    if (!self.isDualAdEnabled) {
        return [DMConfigReader primaryInterAdUnitId];
    }
    
    // 如果主广告位已加载且备用广告位也已加载，比较ECPM
    if (self.isPrimaryAdLoaded && self.isSecondaryAdLoaded) {
        if (self.primaryAdECPM >= self.secondaryAdECPM) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 选择主广告位 (ECPM: $%.6f)", self.primaryAdECPM];
            return self.currentPrimaryAdUnitId;
        } else {
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 选择备用广告位 (ECPM: $%.6f)", self.secondaryAdECPM];
            return self.currentSecondaryAdUnitId;
        }
    }
    
    // 如果只有主广告位加载成功
    if (self.isPrimaryAdLoaded) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 选择主广告位 (仅主广告位可用)"];
        return self.currentPrimaryAdUnitId;
    }
    
    // 如果只有备用广告位加载成功
    if (self.isSecondaryAdLoaded) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 选择备用广告位 (仅备用广告位可用)"];
        return self.currentSecondaryAdUnitId;
    }
    
    // 都没有加载成功，返回主广告位ID
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 无可用广告位，返回主广告位ID"];
    return self.currentPrimaryAdUnitId;
}

- (void)switchToSecondaryAdIfNeeded {
    if (!self.isDualAdEnabled || !self.isSecondaryAdLoaded) {
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 切换到备用广告位"];
    self.currentAdUnitId = self.currentSecondaryAdUnitId;
    self.interstitialAd = self.secondaryInterstitialAdView;
}



#pragma mark - 智能重试机制

- (void)initializeRetrySettings {
    self.maxRetryCount = 5;
    self.currentRetryCount = 0;
    self.baseRetryInterval = 5.0;
    self.totalLoadAttempts = 0;
    self.totalFailures = 0;
    self.lastRetryTime = 0;
    self.isRetryPaused = NO;
    self.retryTimer = nil;
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重试设置初始化完成 - 最大重试次数: %ld", (long)self.maxRetryCount];
}

- (void)resetRetryState {
    self.currentRetryCount = 0;
    self.lastRetryTime = 0;
    self.isRetryPaused = NO;
    [self cancelRetryTimer];
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重试状态已重置"];
}

- (void)scheduleRetryWithDelay:(NSTimeInterval)delay {
    [self cancelRetryTimer];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 安排延迟重试 - 延迟时间: %.1f秒, 重试次数: %ld/%ld", delay, (long)self.currentRetryCount + 1, (long)self.maxRetryCount];
    
    __weak typeof(self) weakSelf = self;
    self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:delay repeats:NO block:^(NSTimer * _Nonnull timer) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf performRetry];
        }
    }];
}

- (BOOL)shouldRetry {
    // 检查是否暂停重试
    if (self.isRetryPaused) {
        NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
        NSTimeInterval pauseDuration = 30 * 60; // 30分钟
        if (currentTime - self.lastRetryTime < pauseDuration) {
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重试暂停中，剩余时间: %.1f分钟", (pauseDuration - (currentTime - self.lastRetryTime)) / 60.0];
            return NO;
        } else {
            // 暂停时间已过，重置状态
            self.isRetryPaused = NO;
            self.currentRetryCount = 0;
            [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重试暂停时间已过，重置重试状态"];
        }
    }
    
    // 检查重试次数
    if (self.currentRetryCount >= self.maxRetryCount) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 已达到最大重试次数 (%ld)，停止重试", (long)self.maxRetryCount];
        return NO;
    }
    
    // 检查失败率
    double failureRate = [self calculateFailureRate];
    if (failureRate > 0.8 && self.totalLoadAttempts >= 10) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 失败率过高 (%.1f%%)，暂停重试30分钟", failureRate * 100];
        self.isRetryPaused = YES;
        self.lastRetryTime = [[NSDate date] timeIntervalSince1970];
        return NO;
    }
    
    return YES;
}

- (NSTimeInterval)calculateRetryDelay {
    // 指数退避算法：5秒、10秒、20秒、40秒、80秒
    NSTimeInterval delay = self.baseRetryInterval * pow(2, self.currentRetryCount);
    NSTimeInterval maxDelay = 80.0;
    return MIN(delay, maxDelay);
}

- (void)performRetry {
    self.currentRetryCount++;
    self.totalLoadAttempts++;
    self.lastRetryTime = [[NSDate date] timeIntervalSince1970];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 执行重试 - 第%ld次重试", (long)self.currentRetryCount];
    
    if (self.isDualAdEnabled) {
        [self loadDualInterstitialAds];
    } else {
        [self loadInter];
    }
}

- (void)cancelRetryTimer {
    if (self.retryTimer) {
        [self.retryTimer invalidate];
        self.retryTimer = nil;
        [IMLogUtils info:IMLogTagAd format:@"📱 [Interstitial] 重试定时器已取消"];
    }
}

- (double)calculateFailureRate {
    if (self.totalLoadAttempts == 0) {
        return 0.0;
    }
    return (double)self.totalFailures / (double)self.totalLoadAttempts;
}

@end
